from functools import wraps
import json
from flask import jsonify, request
from app.utils.log_config import get_logger

# 默认logger
logger = get_logger('error_handler')

def error_handler(logger_instance=None, return_json=True):
    """
    统一异常处理装饰器
    
    Args:
        logger_instance: 日志记录器实例，默认使用error_handler logger
        return_json: 是否返回JSON格式的错误信息
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except Exception as e:
                # 使用指定的logger或默认logger
                log = logger_instance or logger
                log.error(f"函数 {f.__name__} 执行失败: {str(e)}")
                
                # 返回适当的错误响应
                if return_json:
                    return jsonify({
                        'status': 'error',
                        'message': '操作执行失败',
                        'error_type': type(e).__name__
                    }), 500
                else:
                    # 对于返回模板的路由，可以抛出异常或返回错误页面
                    raise
        return decorated_function
    return decorator

def validate_request(*required_fields, location='json'):
    """
    请求参数验证装饰器
    
    Args:
        *required_fields: 必需的字段名列表
        location: 参数位置 ('json', 'form', 'args')
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                if location == 'json':
                    data = request.get_json() or {}
                elif location == 'form':
                    data = request.form.to_dict()
                elif location == 'args':
                    data = request.args.to_dict()
                else:
                    return jsonify({'status': 'error', 'message': '无效的参数位置'}), 400
                
                # 检查必需字段
                missing_fields = [field for field in required_fields if field not in data or not data[field]]
                if missing_fields:
                    return jsonify({
                        'status': 'error',
                        'message': f'缺少必需参数: {", ".join(missing_fields)}'
                    }), 400
                
                return f(*args, **kwargs)
            except Exception as e:
                logger.error(f"参数验证失败: {str(e)}")
                return jsonify({'status': 'error', 'message': '参数验证失败'}), 400
        return decorated_function
    return decorator